﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Devart.Data.Oracle;

namespace ExcelToOracle
{
    public partial class ExportDialog : Form
    {
        private DataTable _table;
        private ImportTemplate _template;

        public ExportDialog(ImportTemplate template, DataTable table)
        {
            InitializeComponent();

            _table = table;
            _template = template;

            dataGridView1.DataSource = _table;
        }

        private void _btnImport_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_ctlEditConnectionString.Text))
            {
                MessageBox.Show("输入连接字符串!");
                return;
            }
            try
            {
                OracleConnection connection = new OracleConnection(_ctlEditConnectionString.Text);

                connection.Open();

                OracleCommand command = connection.CreateCommand();
                connection.Close();
                MessageBox.Show("连接打开成功!");
            }
            catch
            {
                MessageBox.Show("连接打开失败!");
            }
        }

        private void _btnCopySql_Click(object sender, EventArgs e)
        {
            StringBuilder builder = new StringBuilder();

            foreach (DataRow row in _table.Rows)
            {
                builder.AppendFormat("INSERT INTO {0} (", _template.DbTable);
                foreach (FieldTplt constField in _template.Constants)
                {
                    builder.AppendFormat("{0},", constField.TableColumn);
                }
                foreach (FieldTplt field in _template.Fields)
                {
                    builder.AppendFormat("{0},", field.TableColumn);
                }
                builder.Remove(builder.Length - 1, 1);
                builder.Append(") VALUES (");

                foreach (FieldTplt constField in _template.Constants)
                {
                    builder.AppendFormat("'{0}',", row[constField.TableColumn]);
                }
                foreach (FieldTplt field in _template.Fields)
                {
                    builder.AppendFormat("'{0}',", row[field.TableColumn]);
                }
                builder.Remove(builder.Length - 1, 1);
                builder.AppendLine(");");
            }

            Clipboard.SetText(builder.ToString());
            MessageBox.Show("复制成功,请粘贴在数据库中执行!");
        }
    }
}
